Why is this javascript function executing more times per second than it's supposed to